<?php

// +----------------------------------------------------------------------

// | Description: 附件

// +----------------------------------------------------------------------

// +----------------------------------------------------------------------



namespace app\admin\model;



use app\admin\model\Common;

use app\crm\model\Activity;

use app\crm\model\Invoice;

use think\facade\Db;

use think\facade\Filesystem;

use think\Request;

use OSS\OssClient;

use OSS\Core\OssException;



class File extends Common

{



    protected $file_dir = '';

    /**

     * 为了数据库的整洁，同时又不影响Model和Controller的名称

     * 我们约定每个模块的数据表都加上相同的前缀，比如CRM模块用crm作为数据表前缀

     */

    protected $name = 'admin_file';

    protected $module_arr = [

        'other',

        'crm_leads',

        'crm_customer',

        'crm_contacts',

        'crm_business',

        'crm_product',

        'crm_contract',

        'oa_log',

        'oa_examine',

        'oa_examine_travel',

        'work_task',

        'admin_record',

        'oa_travel',

        'hrm_pact',

        'hrm_file',

        'crm_invoice',

        'crm_activity',

        'crm_visit',

        'crm_receivables'

    ];



    /**

     * @param array $files

     * @param array $param

     * @param string $x 裁剪图的长

     * @param string $y 裁剪图的宽

     * @return array|false

     * @author Mr.Li longfei

     * @create 2021-05-26 14:07

     */

    public function createData($files, $param = [], $x = '150', $y = '150')

    {
        
        $this->file_dir = config('app.file_dir');

        if (empty($files)) {

            $this->error = '请选择上传文件';

            return false;

        }

        

        $param['type'] = 'img';

        $saveData = [];


        try {

            validate(

                [

                    'file' => [

                        // 限制文件大小(单位b)，这里限制为4M

                        // 限制文件大小(单位b)，这里限制为50M

                        'fileSize' => 50 * 1024 * 1024,

                        // 限制文件后缀，多个后缀以英文逗号分割

                        'fileExt'  => 'gif,jpg,png,jpeg'

                    ]

                ],

                [

                    'file.fileSize' => '文件太大',

                    'file.fileExt' => '不支持的文件后缀',

                ]

            )->check(['file' => $files]);


            // 保存图片在服务器上
            $savename = Filesystem::disk('public')->putFile( 'image', $files);

            $savename_nowater = Filesystem::disk('public')->putFile( 'image_nowater', $files); // 无水印图片实例

            /////////////////////////////////////////////////////////无水印一/////////////////////////////////////////////////
            
            
            /////////////////////////////////////////////////////////水印二/////////////////////////////////////////////////
            $dst_path = "./storage/".$savename;
            // 获取图片信息
            $mark = getimagesize($dst_path);
            //创建图片的实例
            $dst = imagecreatefromstring(file_get_contents($dst_path));
            
            // echo "111";
            // exit;

            
            //打上文字
            $font = './font/msyh.ttc';//字体路径
            $content = "欣奕除疤";
            // $black = imagecolorallocate($dst, 0x00, 0x00, 0x00);//字体颜色
            //设置字体的颜色及透明图
            $col = imagecolorallocatealpha($dst, 255, 255, 255, 100);
            
            $x_length = $mark[0];
            $y_length = $mark[1];
            if($x_length>500){
                $font_size = $mark[0]/60;
                $water_w=$mark[0]/5;
                $water_h=$mark[1]/6;
            }else{
                $font_size = 10;
                $water_w=$mark[0]/3;
                $water_h=$mark[1]/4;
            }
            
            for ($x = 10; $x < $x_length; $x) {
                for ($y = 20; $y < $y_length; $y) {
                    imagettftext($dst, $font_size, '45', $x, $y, $col, $font, $content);
                    $y += $water_h;
                }
                $x += $water_w;
            }
            
            //输出图片
            $dst_new = './storage/'.$savename;//存储的路径

            list($dst_w, $dst_h, $dst_type) = getimagesize($dst_path);
            ob_clean();
            switch ($dst_type) {
                case 1://GIF
                    imagegif($dst,$dst_new);
                    break;
                case 2://JPG
                    imagejpeg($dst,$dst_new);
                    break;
                case 3://PNG
                    imagepng($dst,$dst_new);
                    break;
                default:
                    break;
            }
            imagedestroy($dst);

            //////////////////////////////////////////////////////////////////////////////////////////

            $image = \think\Image::open('storage/'.$savename);

            $accessKeyId = "LTAI4FopKKqp8ZE7qMh7x8rL";
            $accessKeySecret = "QU8minZbbZFXsHl9EHq8BmQo3S27lV";
            $endpoint = "oss-cn-zhangjiakou.aliyuncs.com";
            $bucket = "xinyis2017";

            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);

            // echo $savename;echo "<br/>";
            $oss_url = substr($savename,6);
            // echo $oss_url;
            // echo $url;

            // echo "<pre>";
            // print_r($files);

            // echo "<pre>";
            // print_r($image);
            // exit;

            $saveName = [];

            if(is_array($files)){

                $this->error = '上传失败';

                return false;

                foreach($files as $file) {

                    $saveName[] = \think\facade\Filesystem::disk('aliyun')->putFile( $this->file_dir, $file);

                }

            }else{

                $originName = $files->getOriginalName();

                $size = $files->getSize();

                $ext = $files->getOriginalExtension();

                // echo "1:".$originName;echo "<br/>";
                // echo "2:".$size;echo "<br/>";
                // echo "3:".$ext;echo "<br/>";

                // exit;

                if($originName == 'blob'){ //判断截图

                  // $res =  validate(['image'=>'filesize:10240|fileExt:png|image:200,200,jpg'])->check([$files]);

                    // $ext = 'png';

                    // $saveData['save_name'] = \think\facade\Filesystem::disk('aliyun')->putFileAs( $this->file_dir, $files,'logo.png');

                    // 水印图片上传
                    $content = './storage/'.$savename;// 服务器路径
                    $object  = "xy_img/".$oss_url;// OSS路径
                    
                    $ossClient->uploadFile($bucket, $object,$content);// 上传
                    unlink($content);

                    // 无水印图片上传
                    $content_no = './storage/'.$savename_nowater;// 服务器路径
                    $object_no  = "xy_img_nowater/".$oss_url;// OSS路径
                    
                    $ossClient->uploadFile($bucket, $object_no,$content_no);// 上传
                    unlink($content_no);

                    $saveData['save_name'] = $object; // 水印图片
                    $saveData['save_name_no'] = $object_no; // 无水印图片

                }else{
                    // 上传OSS
                    // $saveData['save_name'] =  \think\facade\Filesystem::disk('aliyun')->putFile( $this->file_dir, $files);

                    // 水印图片上传
                    $content = './storage/'.$savename;// 服务器路径
                    $object  = "xy_img/".$oss_url;// OSS路径
                    
                    $ossClient->uploadFile($bucket, $object,$content);// 上传
                    unlink($content);


                    // 无水印图片上传
                    $content_no = './storage/'.$savename_nowater;// 服务器路径
                    $object_no  = "xy_img_nowater/".$oss_url;// OSS路径
                    
                    $ossClient->uploadFile($bucket, $object_no,$content_no);// 上传
                    unlink($content_no);

                    $saveData['save_name'] = $object; // 水印图片
                    $saveData['save_name_no'] = $object_no; // 无水印图片

                }

                //附件信息存储

                $saveData['name'] =  $originName;

                $saveData['size'] = $size;

                $saveData['create_user_id'] = $param['create_user_id'];

                $saveData['create_time'] = time();

                $saveData['file_path_thumb'] = $thumbSaveName ?? '';

                $saveData['types'] = $param['type'] ? : 'file';

                $saveData['file_path'] =  $saveData['save_name'];

                if(!$saveData['save_name']){

                    $this->error = '上传失败';

                    return false;

                }



                // echo "<pre>";
                // print_r($saveData);
                // exit;

                $this->data($saveData)->save();

                $saveData['save_path'] = $saveData['file_path'];

                $saveData['file_path'] = config('app.img_url') .$saveData['file_path'];

                $saveData['id'] = $this->id;

                //$name = md5(time().mt_rand(1,9999).$files->getOriginalName()).'.'.$ext;

                // if(\think\facade\Filesystem::disk('aliyun')->putFileAs( 'dxj_img', $files,$name)){

            }



        }catch (\Exception $e) {

            $this->error = $e->getMessage();

           return false;

        } catch (\think\exception\ValidateException $e) {

            $this->error = $e->getMessage();

            return false;

        }

        return $saveData;





    }



    /**

     * 修改上传文件名

     * @param  [type] $save_name [description]

     * @param  [type] $name      [description]

     * @return [type]            [description]

     */

    public function updateNameBySaveName($save_name,$name)

    {

        $flag = $this->where(['save_name' => $save_name])->setField('name',$name);

        if ( $flag ) {

            return true;

        } else {

            $this->error = '操作失败';

            return false;

        }

    }



    /**

     * [delFileById 删除附件]

     * @author Mr.Li

     * @param     $save_name 附件保存名称

     * @param     $param [module : 模块, module_id : 模块ID]

     * @return    [array]

     */

    public function delFileBySaveName($save_name, $param = [])

    {

        if (!$save_name) {

            $this->error = '请选择需要删除的附件';

            return false;

        }

        $fileInfo = $this->where(['save_name' => trim($save_name)])->find();

        if (!$fileInfo) {

            $this->error = '附件不存在或已删除';

            return false;

        }

        $file_id = $fileInfo['file_id'];

        $res = db('admin_file')->where(['file_id' => $file_id])->delete();

        if ($res) {

            @unlink($fileInfo['file_path']);//删除文件

            if ($fileInfo['file_path_thumb']) @unlink($fileInfo['file_path_thumb']);

            //处理附表信息

            if (in_array($param['module'], $this->module_arr)) {

                switch ($param['module']) {

                    case 'crm_leads' : $r = db('crm_leads_file'); break;

                    case 'crm_customer' : $r = db('crm_customer_file'); break;

                    case 'crm_contacts' : $r = db('crm_contacts_file'); break;

                    case 'crm_business' : $r = db('crm_business_file'); break;

                    case 'crm_product' : $r = db('crm_product_file'); break;

                    case 'crm_contract' : $r = db('crm_contract_file'); break;

                    case 'oa_log' : $r = db('oa_log_file'); break;

                    case 'oa_examine' : $r = db('oa_examine_file'); break;

                    case 'work_task' : $r = db('work_task_file'); break;

                    case 'admin_record' : $r = db('admin_record_file'); break;

                    case 'oa_travel' : $r = db('oa_travel_file'); break;

                    case 'hrm_pact' : $r = db('hrm_pact_file'); break;

                    case 'hrm_file' : $r = db('hrm_user_file'); break;

                    case 'crm_invoice' : $r = db('crm_invoice_file'); break;

                    case 'crm_activity': $r = db('crm_activity_file'); break;

                    case 'crm_visit': $r = db('crm_visit_file'); break;

                    case 'crm_receivables': $r = db('crm_receivables_file'); break;

                    default : break;

                }

                $resDel = $r->where(['file_id'=>$file_id])->delete();

            }

            return true;

        } else {

            $this->error = '删除失败';

            return false;

        }

    }



    /**

     * 根据主键获取详情

     * @author Mr.Li

     * @param  array   $param  [description]

     */

    public function getDataBySaveName($save_name = '')

    {

        if (!$save_name) {

            $this->error = '参数错误';

            return false;

        }

        $data = $this->where(['save_name' => trim($save_name)])->find();

        $data['full_path'] = getFullPath($data['file_path']);

        $data['full_path_thumb'] = getFullPath($data['file_path_thumb']);

        if (!$data) {

            $this->error = '数据不存在或已删除';

            return false;

        }

        return $data;

    }



    /**

     * 根据ID获取列表

     * @author Mr.Li

     * @param  string   module  [类型]

     * @param  string   by = all 全部（不分页）

     * @param  int   module_id  [类型ID]

     */

    public function getDataList($request, $by = '')

    {

        if (!in_array($request['module'], $this->module_arr) || !$request['module_id']) {

            $this->error = '参数错误';

            return false;

        }

        $module_ids = $request['module_id'];

        if (!is_array($request['module_id'])) {

            $module_ids = array($request['module_id']);

        }

        $moduleName = $request['module'];



        switch ($request['module']) {

            case 'crm_leads' : $r = db('crm_leads_file'); $module = db('crm_leads'); break;

            case 'crm_customer' : $r = db('crm_customer_file'); $module = db('crm_customer'); break;

            case 'crm_contacts' : $r = db('crm_contacts_file'); $module = db('crm_contacts'); break;

            case 'crm_business' : $r = db('crm_business_file'); $module = db('crm_business'); break;

            case 'crm_product' : $r = db('crm_product_file'); $module = db('crm_product'); break;

            case 'crm_contract' : $r = db('crm_contract_file'); $module = db('crm_contract'); break;

            case 'oa_log' : $r = db('oa_log_file'); $module = db('oa_log'); break;

            case 'oa_examine' : $r = db('oa_examine_file'); $module = db('oa_examine'); break;

            case 'oa_examine_travel' : $r = db('oa_examine_travel_file'); $module = db('oa_examine_travel'); break;

            case 'work_task' : $r = db('work_task_file'); $module = db('task'); break;

            case 'admin_record' : $r = db('admin_record_file'); $module = db('admin_record'); break;

            case 'oa_travel' : $r = db('oa_travel_file'); $module = db('oa_travel'); break;

            case 'hrm_pact' : $r = db('hrm_pact_file'); $module = db('hrm_pact'); break;

            case 'hrm_file' : $r = db('hrm_user_file'); $module = db('admin_user'); break;

            case 'crm_invoice' : $r = db('crm_invoice_file'); $module = db('crm_invoice'); break;

            case 'crm_activity' : $r = db('crm_activity_file'); $module = db('crm_activity'); break;

            case 'crm_visit' : $r = db('crm_visit_file'); $module = db('crm_visit'); break;

            case 'crm_receivables' : $r = db('crm_receivables_file'); $module = db('crm_receivables'); break;

            default : break;

        }

        if ($r) {

            $fileIds = $r->where([$module->getPk() => ['in',$module_ids]])->column('file_id');

            $request['file_id'] = ['in', $fileIds];

        }

        unset($request['module']);

        unset($request['module_id']);

        unset($request['by']);



        # 查询活动附件，用于判断是否可以删除附件（活动添加的附件只能在活动中删除）

        $activityFileIds = [];

        $activityType = ['crm_leads' => 1, 'crm_customer' => 2, 'crm_contacts' => 3, 'crm_business' => 5, 'crm_contract' => 6];

        if (!empty($activityType[$moduleName])) {

            $activityFileIds = db('crm_activity')->alias('activity')

                ->join('__CRM_ACTIVITY_FILE__ file', 'file.activity_id = activity.activity_id', 'LEFT')

                ->where(['type' => 1, 'activity_type' => $activityType[$moduleName], 'activity_type_id' => ['in', $module_ids]])

                ->column('file.file_id');

            $activityFileIds = array_filter($activityFileIds);

        }



        $userModel = new \app\admin\model\User();

        $request = $this->fmtRequest( $request );

        $map = $request['map'];

        $order = 'create_time desc';

        $dataCount = $this->where($map)->count('file_id');

        if ($by == 'all') {

            $list = Db::name('AdminFile')->where($map)->order($order)->select();

        } else {

            $list = Db::name('AdminFile')->where($map)->page($request['page'], $request['limit'])->order($order)->select();

        }

        foreach ($list as $k=>$v) {

            $createUserInfo = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : [];

            $list[$k]['size'] = format_bytes($v['size']); //字节转换

            $list[$k]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);

            $list[$k]['create_user_id_info'] = $createUserInfo;

            $list[$k]['createName'] = !empty($createUserInfo['realname']) ? $createUserInfo['realname'] : '';

            $list[$k]['ext'] = getExtension($v['save_name']);

            $list[$k]['file_path'] = getFullPath($v['file_path']);

            $list[$k]['file_path_thumb'] = getFullPath($v['file_path_thumb']);

            $list[$k]['readOnly'] = !empty($activityType[$moduleName]) && in_array($v['file_id'], $activityFileIds) ? 1 : 0; # 活动中上次的附件，只能在活动中删除

        }

        $data = [];

        $data['list'] = $list ? : [];

        $data['dataCount'] = $dataCount ? : 0;

        return $data;

    }



    /**

     * 根据表、字段更新上传图片

     * @author Mr.Li

     * @param  $file 附件信息

     * @param  $module 模块（判断权限）,一般是控制器，并且和表名一致

     * @param  $module_id 模块ID（判断权限）

     * @param  $file 字段

     * @param  $thumb_field 缩略图字段

     * @param  $x 裁剪宽度

     * @param  $y 裁剪高度

     */

    public function updateByField($file, $module, $module_id, $field, $thumb_field = '', $x = '150', $y = '150')

    {

        if (empty($module) || empty($module_id) || empty($field)) {

            $this->error = '参数错误';

            return false;

        }



        $info = $file->move(FILE_PATH . 'public' . DS . 'uploads'); //验证规则

        $fileInfo = $info->getInfo(); //附件数据

        $saveName = '';

        $thumbSaveName = '';

        if ($info) {

            //如果是图片类型，生成缩略图

            $ext = $info->getExtension();

            $saveName = $info->getSaveName();

            $fileName = $info->getFilename();

            $thumbSaveName = str_replace(DS, DS.'thumb_', $saveName);

            //附件信息存储

            $saveData = [];



            if ($thumb_field) {

                // $image = \think\Image::open($file);

                $image = \think\Image::open(UPLOAD_PATH . str_replace(DS, '/', $saveName));

                $thumbSaveName = str_replace(DS, DS.'thumb_', $saveName);

                $image->thumb($x, $y,\think\Image::THUMB_FILLED)->save(FILE_PATH . 'public'. DS .'uploads'. DS .$thumbSaveName); //THUMB_SCALING 或 THUMB_FILLED

                $saveData[$thumb_field] = $thumbSaveName ? UPLOAD_PATH . str_replace(DS, '/', $thumbSaveName) : '';

            }

            $saveData[$field] = UPLOAD_PATH . str_replace(DS, '/', $saveName);

            switch ($module) {

                case 'crm_customer' : $moduleModel = new \app\crm\model\Customer(); break;

                case 'crm_contacts' : $moduleModel = new \app\crm\model\Contacts(); break;

                case 'crm_business' : $moduleModel = new \app\crm\model\Business(); break;

                case 'crm_product' : $moduleModel = new \app\crm\model\Product(); break;

                case 'crm_contract' : $moduleModel = new \app\crm\model\Contract(); break;

                case 'User' : $moduleModel = new \app\admin\model\User(); break;

                case 'admin_system': $moduleModel = new \app\admin\model\System(); break;

                case 'crm_invoice' : $moduleModel = new Invoice(); break;

                case 'crm_activity' : $moduleModel = new Activity(); break;

                case 'crm_receivables' : $moduleModel = new \app\crm\model\Receivables(); break;

                case 'crm_visit' : $moduleModel = new \app\crm\model\Visit(); break;

            }



            $resFile = $moduleModel->allowField([$field,$thumb_field])->save($saveData, [$moduleModel->getPk() => $module_id]);

            if (!$resFile) {

                $this->error = '上传失败';

                return false;

            }

            return true;

        }

    }



    /**

     * 根据ID保存，处理逻辑关系

     * @author Mr.Li

     * @param  $ids 附件ID数组

     * @param  $module 表名

     * @param  $module_id 模块ID

     */

    public function createDataById($ids, $module, $module_id)

    {

        if (!$ids || !in_array($module, $this->module_arr) || !$module_id) {

            $this->error = '参数错误';

            return false;

        }



        switch (trim($module)) {

            case 'crm_customer' : $rDb = db('crm_customer_file'); $r_name = 'customer_id'; break;

            case 'crm_contacts' : $rDb = db('crm_contacts_file'); $r_name = 'contacts_id'; break;

            case 'crm_business' : $rDb = db('crm_business_file'); $r_name = 'business_id'; break;

            case 'crm_product' : $rDb = db('crm_product_file'); $r_name = 'product_id'; break;

            case 'crm_contract' : $rDb = db('crm_contract_file'); $r_name = 'contract_id'; break;

            case 'oa_log' : $rDb = db('oa_log_file'); $r_name = 'log_id'; break;

            case 'oa_examine' : $rDb = db('oa_examine_file'); $r_name = 'examine_id'; break;

            case 'oa_examine_travel' : $rDb = db('oa_examine_travel_file'); $r_name = 'travel_id'; break;

            case 'admin_record' : $rDb = db('admin_record_file'); $r_name = 'record_id'; break;

            case 'oa_travel' : $rDb = db('oa_travel_file'); $r_name = 'travel_id'; break;

            case 'crm_invoice' : $rDb = db('crm_invoice_file'); $r_name = 'invoice_id'; break;

            case 'crm_activity' : $rDb = db('crm_activity_file'); $r_name = 'activity_id'; break;

            case 'crm_visit' : $rDb = db('crm_visit_file'); $r_name = 'activity_id'; break;

            case 'crm_receivables' : $rDb = db('crm_receivables_file'); $r_name = 'receivables_id'; break;

        }



        $res_success = true;

        $data = [];

        $data[$r_name] = intval ($module_id);

        foreach ($ids as $v) {

            $data['file_id'] = intval($v);

            if (!$rDb->insert($data)) {

                $res_success = false;

            }

        }

        if ($res_success == false) {

            $this->error = '附件上传失败';

        }

        return true;

    }





    /**

     * 删除关系表附件

     * @author Mr.Li

     * @param  $module 模块

     * @param  $module_id 模块ID

     */

    public function delRFileByModule($module, $module_id)

    {

        if (in_array($module,$this->module_arr) && $module_id) {

            switch ($module) {

                case 'crm_leads' :

                    $r = db('crm_leads_file');

                    $r_name = 'leads_id';

                    break;

                case 'crm_customer' :

                    $r = db('crm_customer_file');

                    $r_name = 'customer_id';

                    break;

                case 'crm_contacts' :

                    $r = db('crm_contacts_file');

                    $r_name = 'contacts_id';

                    break;

                case 'crm_business' :

                    $r = db('crm_business_file');

                    $r_name = 'business_id';

                    break;

                case 'crm_product' :

                    $r = db('crm_product_file');

                    $r_name = 'product_id';

                    break;

                case 'crm_contract' :

                    $r = db('crm_contract_file');

                    $r_name = 'contract_id';

                    break;

                case 'oa_log' :

                    $r = db('oa_log_file');

                    $r_name = 'log_id';

                    break;

                case 'oa_examine' :

                    $r = db('oa_examine_file');

                    $r_name = 'examine_id';

                    break;

                case 'work_task' :

                    $r = db('work_task_file');

                    $r_name = 'task_id';

                    break;

                case 'admin_record' :

                    $r = db('admin_record_file');

                    $r_name = 'record_id';

                    break;

                case 'oa_travel' :

                    $r = db('oa_travel_file');

                    $r_name = 'travel_id';

                    break;

                case 'hrm_pact' :

                    $r = db('hrm_pact_file');

                    $r_name = 'pact_id';

                    break;

                case 'hrm_file' :

                    $r = db('hrm_user_file');

                    $r_name = 'user_id';

                    break;

                case 'crm_invoice' :

                    $r = db('crm_invoice_file');

                    $r_name = 'invoice_id'; break;

                case 'crm_visit' :

                    $r = db('crm_visit_file');

                    $r_name = 'visit_id';

                    break;

                case 'crm_activity' :

                    $r = db('crm_activity_file');

                    $r_name = 'activity_id';

                    break;

                case 'crm_receivables' :

                    $r = db('crm_receivables_file');

                    $r_name = 'receivables_id';

                default : break;

            }

            $rWhere = [];

            if(!is_array($module_id)){

                $module_id = [intval ($module_id)];

            }

            $rWhere[$r_name] = ['in',$module_id];

            $rFileIds = $r->where($rWhere)->column('file_id');

            $rRes = $r->where($rWhere)->delete();

            if ($rRes && $rFileIds) {

                $fileList = db('admin_file')->where(['file_id' => ['in',$rFileIds]])->field('file_path,file_path_thumb')->select();

                foreach ($fileList as $v) {

                    //删除文件

                    @unlink($v['file_path']);

                    @unlink($v['file_path_thumb']);

                }

            }

        }

    }



    /**

     * 全部删除(活动、产品)

     *

     * @param $param

     * @return bool

     * @throws \think\Exception

     * @throws \think\exception\PDOException

     */

    public function deleteAll($param)

    {

        if (!empty($param['module']) && !empty($param['module_id'])) {

            $module     = db('crm_activity_file');

            $primaryKey = 'activity_id';



            switch ($param['module']) {

                case 'crm_activity' : $module = db('crm_activity_file'); $primaryKey = 'activity_id'; break;

                case 'crm_product' : $module = db('crm_product_file'); $primaryKey = 'product_id'; break;

            }



            $fileIds = $module->where($primaryKey, $param['module_id'])->column('file_id');



            # 删除关联数据

            $module->where($primaryKey, $param['module_id'])->delete();



            # 删除附件

            db('admin_file')->whereIn('file_id', $fileIds)->delete();

        }



        if (!empty($param['file_id'])) {

            db('admin_file')->whereIn('file_id', $param['file_id'])->delete();

        }



        return true;

    }



    /**

     * @param array $files

     * @param array $param

     * @return array|false

     * @author Mr.Li longfei

     * @create 2021-05-26 14:07

     */

    public function excelData($files, $param = [])

    {

        if (empty($files)) {

            $this->error = '请选择上传文件';

            return false;

        }

        $param['type'] = 'excel';

        $saveData = [];

        try {

            validate(

                [

                    'file' => [

                        // 限制文件大小(单位b)，这里限制为2M

                        'fileSize' => 40 * 1024 * 1024,

                        // 限制文件后缀，多个后缀以英文逗号分割

                        'fileExt'  => 'xls,xlsx'

                    ]

                ],

                [

                    'file.fileSize' => '文件太大',

                    'file.fileExt' => '不支持的文件后缀',

                ]

            )->check(['file' => $files]);



            if(is_array($files)){

                $this->error = '上传失败';

                return false;

            }else{

                $originName = $files->getOriginalName();

                $size = $files->getSize();

                $ext = $files->getOriginalExtension();

                $saveName = \think\facade\Filesystem::disk('public')->putFile( 'dxj_excel', $files);

                $nameArr = explode('\/', $saveName);

                $saveData['save_name'] = implode('/', $nameArr);

                //附件信息存储

                $saveData['name'] =  $originName;

                $saveData['size'] = $size;

                $saveData['create_user_id'] = $param['create_user_id'];

                $saveData['create_time'] = time();

                $saveData['file_path_thumb'] = $thumbSaveName ?? '';

                $saveData['types'] = 'file';

                $saveData['file_path'] =  $saveData['save_name'];

                if(!$saveData['save_name']){

                    $this->error = '上传失败';

                    return false;

                }



//                $this->data($saveData)->save();

                $saveData['file_path'] = "";

                $saveData['id'] = $this->id;

            }



        }catch (\Exception $e) {

            $this->error = $e->getMessage();

            return false;

        }



        return $saveData;





    }


    /**

     * @param array $files

     * @param array $param

     * @param string $x 裁剪图的长

     * @param string $y 裁剪图的宽

     * @return array|false

     * @author Mr.Li longfei

     * @create 2021-05-26 14:07

     */

    public function uploadBanner($files, $param = [], $x = '150', $y = '150')

    {
        
        $this->file_dir = config('app.file_dir');

        if (empty($files)) {

            $this->error = '请选择上传文件';

            return false;

        }

        

        $param['type'] = 'img';

        $saveData = [];


        try {

            validate(

                [

                    'file' => [

                        // 限制文件大小(单位b)，这里限制为4M

                        // 限制文件大小(单位b)，这里限制为50M

                        'fileSize' => 50 * 1024 * 1024,

                        // 限制文件后缀，多个后缀以英文逗号分割

                        'fileExt'  => 'gif,jpg,png,jpeg'

                    ]

                ],

                [

                    'file.fileSize' => '文件太大',

                    'file.fileExt' => '不支持的文件后缀',

                ]

            )->check(['file' => $files]);


            // 保存图片在服务器上
            $savename = Filesystem::disk('public')->putFile( 'image', $files);

            $image = \think\Image::open('storage/'.$savename);

            $accessKeyId = "LTAI4FopKKqp8ZE7qMh7x8rL";
            $accessKeySecret = "QU8minZbbZFXsHl9EHq8BmQo3S27lV";
            $endpoint = "oss-cn-zhangjiakou.aliyuncs.com";
            $bucket = "xinyis2017";

            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);

            // echo $savename;echo "<br/>";
            $oss_url = substr($savename,6);
            

            $saveName = [];

            if(is_array($files)){

                $this->error = '上传失败';

                return false;

                foreach($files as $file) {

                    $saveName[] = \think\facade\Filesystem::disk('aliyun')->putFile( $this->file_dir, $file);

                }

            }else{

                $originName = $files->getOriginalName();

                $size = $files->getSize();

                $ext = $files->getOriginalExtension();

                // echo "1:".$originName;echo "<br/>";
                // echo "2:".$size;echo "<br/>";
                // echo "3:".$ext;echo "<br/>";

                // exit;

                if($originName == 'blob'){ //判断截图

                    $content = './storage/'.$savename;// 服务器路径
                    $object  = "xy_img/".$oss_url;// OSS路径
                    
                    $ossClient->uploadFile($bucket, $object,$content);// 上传
                    unlink($content);

                    $saveData['save_name'] = $object;

                }else{
                    // 上传OSS
                    // $saveData['save_name'] =  \think\facade\Filesystem::disk('aliyun')->putFile( $this->file_dir, $files);

                    $content = './storage/'.$savename;// 服务器路径
                    $object  = "xy_img/".$oss_url;// OSS路径
                    
                    $ossClient->uploadFile($bucket, $object,$content);// 上传
                    unlink($content);

                    $saveData['save_name'] = $object;

                }

                //附件信息存储

                $saveData['name'] =  $originName;

                $saveData['size'] = $size;

                $saveData['create_user_id'] = $param['create_user_id'];

                $saveData['create_time'] = time();

                $saveData['file_path_thumb'] = $thumbSaveName ?? '';

                $saveData['types'] = $param['type'] ? : 'file';

                $saveData['file_path'] =  $saveData['save_name'];

                if(!$saveData['save_name']){

                    $this->error = '上传失败';

                    return false;

                }



                
                $this->data($saveData)->save();

                $saveData['save_path'] = $saveData['file_path'];

                $saveData['file_path'] = config('app.img_url') .$saveData['file_path'];

                $saveData['id'] = $this->id;

            }



        }catch (\Exception $e) {

            $this->error = $e->getMessage();

           return false;

        } catch (\think\exception\ValidateException $e) {

            $this->error = $e->getMessage();

            return false;

        }

        return $saveData;
    }

}

